package com.qf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.Exception.MyException;
import com.qf.domain.EbookEntry;
import com.qf.mapper.EbookEntryMapper;
import com.qf.service.EbookEntryService;
import com.qf.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.List;

@Service
public class EbookEntryServiceimpl implements EbookEntryService {
    @Autowired
    private EbookEntryMapper ebookEntryMapper;
    @Override
    public ResultVO findByPage(Integer page, Integer size, Integer type) {
//        int i=10/0;
        //分页
        PageHelper.startPage(page,size);
        //查询
        List<EbookEntry> data= ebookEntryMapper.findByType(type);
        //封装PageInfo
        PageInfo<EbookEntry> pageInfo=new PageInfo<>(data);
        //封装ResultVo
        ResultVO vo=new ResultVO();
        vo.setCount(pageInfo.getTotal());
        vo.setData(pageInfo.getList());
        //返回ResultVo
        return vo;
    }

    @Override
    @Transactional //声明事务   如果在测试中开启事务那么会自动回滚不提交
    public void addbook(EbookEntry ebookEntry) {
        //根据穿过来的数据查询，
        int cont=ebookEntryMapper.insertbook(ebookEntry);

        if (cont!=1){
            throw new MyException("添加失败",500);
        }


    }

    @Override
    public ResultVO findId(Integer id) {
        if (id!=null){
            EbookEntry ebookEntry= ebookEntryMapper.findID(id);
            if (ebookEntry==null){
                throw new MyException("您查的书未找到或者不存在",500);
            }else {
                ResultVO resultVO=new ResultVO();
                resultVO.setData(ebookEntry);
                return resultVO;
            }
        }else {
            throw new MyException("您查的书未找到或者不存在",500);
        }


    }

    @Override
    public ResultVO updatebook(EbookEntry ebookEntry) {
        ResultVO resultVO=new ResultVO();
        if (ebookEntry==null){
            throw new MyException("您要修改的数据没有传送成功",500);
        }else {
            int i=ebookEntryMapper.updatebook(ebookEntry);
            if (i!=1){
                resultVO.setCode(500);
                resultVO.setMsg("添加失败");
                return resultVO;
            }else {
                return resultVO;
            }
        }
    }

    @Override
    public int deletebook(Integer id) {
        if (id!=null){
            int i= ebookEntryMapper.deletebook(id);
            if (i!=1){
                throw new MyException("您查的书未找到或者不存在",500);
            }else {
               return 1;
            }
        }else {
            throw new MyException("您查的书未找到或者不存在",500);
        }
    }
}
